//
//  SendNewsViewController.swift
//  weibo1
//
//  Created by 李进 on 15/10/25.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit


/// MARK: - 发送微博控制器
class SendNewsViewController: UIViewController {
    
    override func loadView() {
        super.loadView()
        setNavgationItem()
        
        setupUI()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //添加通知中心
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }

    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        //设置第一响应者
        //textview.becomeFirstResponder()
    }
    
    /// 监听通知
    ///
    /// - parameter n: 通知中心本身参数
    @objc func keyBoardChange(n: NSNotification){
        
        // 1. 获取目标的 rect - 字典中的`结构体`是 NSValue
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 获取目标的动画时长 - 字典中的数值是 NSNumber
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        // 动画曲线数值
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        // 2. 更新约束
        accKeyBoardTool.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        // 3. 动画
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    /// 移除通知中心
     deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: -设置textview 上面的控制器
    func setupUI(){
       // prepareToolbar()
        //添加控件
        view.addSubview(textview)
        textview.addSubview(titleLabel)
        view.addSubview(accKeyBoardTool)
        //view.addSubview(tempAddImage)
        addChildViewController(addImage)
        view.insertSubview(addImage.view, belowSubview: accKeyBoardTool)
        
    
        textview.inputView = keyBoard
        
        
        //设置自动布局
        textview.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideTop)
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
        }
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textview.snp_left).offset(5)
            make.top.equalTo(textview.snp_top).offset(8)
        }
        
        accKeyBoardTool.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        
        addImage.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0.001)
        }
        
    }
    
    
    //MARK: -添加navigation 上的item
    func setNavgationItem(){
        
        //添加navigation 上的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    //MARK: -实现监听方法
    func back(){
       // print("退出")
        //关闭键盘
        textview.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// MARK: 发布微博按钮
    func send(){
       // print("\(textview.attributedText)")
        //TODO: 多文件上传
        let array = addImage.arrayList.last
        
            
            SWWebTools.shareWebTools.sendNewMessage(textview.emoticonText, image: array) { (result, error) -> () in
                //print(result)
            
        }
        
        
        
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    ///添加图片按键
    func addAndOptionImage(){
        //测试
        // 0. 判断如果已经更新了约束，不再执行后续代码
        if addImage.view.frame.height > 0 {
            return
        }
        
        // 1. 修改照片选择控制器视图的约束
        addImage.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        // 2. 修改文本视图的约束 - 重建约束 - 会将之前`textView`的所有的约束删除
        textview.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(addImage.view.snp_top)
        }
        
//        
//        addImage.view.snp_makeConstraints { (make) -> Void in
//            make.left.equalTo(view.snp_left)
//            make.right.equalTo(view.snp_right)
//            make.bottom.equalTo(view.snp_bottom)
//            make.top.equalTo(300)
        
            
        
        self.view.layoutIfNeeded()
        
       // presentViewController(addImage, animated: true, completion: nil)
    }
    /// MARK: 点击toolbar上的按钮
    func selectEmoticon(){
       // print("点击了item")
        
        //取消第一响应者
        textview.resignFirstResponder()
        
        //设置使用什么键盘
        textview.inputView = textview.inputView == nil ? keyBoard : nil
        
        //重新注册为第一响应者
        textview.becomeFirstResponder()
        
    }
    //测试
    private lazy var tempAddImage:appendPhotosCollectionView = appendPhotosCollectionView()
    private lazy var addImage: appendPhotosVC = appendPhotosVC()
    private lazy var keyBoard: EmoticonsView = EmoticonsView(selectedEmoticon: { (emoticon) -> () in
        self.textview.insertEmoticon(emoticon)
    })
    //懒加载控件
    private lazy var textview:UITextView = {
        let tv = UITextView()
        //设置textview中的字体大小
        tv.font = UIFont.systemFontOfSize(20)
        tv.alwaysBounceVertical = true
        //拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        tv.delegate = self
        return tv
    }()
    //占位label
    private lazy var titleLabel: UILabel = {
        let title = UILabel(title: "分享新鲜事...")
        
        title.font = UIFont.systemFontOfSize(20)
        
        title.textColor = UIColor.lightGrayColor()
        
        title.sizeToFit()
        
        return title
    }()
    //键盘的辅助输入框
    private lazy var accKeyBoardTool:UIToolbar = {
    
        let toolBar1 = UIToolbar()
        
        toolBar1.backgroundColor = UIColor.orangeColor()
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"addAndOptionImage"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var itemS = [UIBarButtonItem]()
    
        for dic in itemSettings{
            
            // let image = UIImage(named: dic["imageName"]!)
            //去处图片上面渲染的模版
            //let newimage = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
            
            let item = UIBarButtonItem(imageName: dic["imageName"]!, target: self, actionName: dic["actionName"])
            
            itemS.append(item)
            itemS.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        itemS.removeLast()
        toolBar1.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        toolBar1.items = itemS
        
        return toolBar1
        
    }()
    //MARK: －准备toolbar《《无效》》
    func prepareToolbar(){
        
        accKeyBoardTool.backgroundColor = UIColor.orangeColor()
        
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var itemS = [UIBarButtonItem]()
        
        for dic in itemSettings{
            
            let image = UIImage(named: dic["imageName"]!)
            //去处图片上面渲染的模版
            let newimage = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
            
            let item = UIBarButtonItem(image: newimage, style: UIBarButtonItemStyle.Plain, target: self, action: "actionName")
            
            itemS.append(item)
            itemS.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        itemS.removeLast()
        accKeyBoardTool.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        accKeyBoardTool.items = itemS
        
    }
    
}

// MARK: - textview 的代理方法
extension SendNewsViewController: UITextViewDelegate{
  
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textview.hasText()

        titleLabel.hidden = textview.hasText()
    }
}
